using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using F8Framework.Core;
using F8Framework.Launcher;
using System.Collections.Specialized;
using R3;
using R3.Triggers;
using System.Linq;

public class UIGameMain : BaseView
{
    private GameViewModel _viewModel;
    private List<CardItem> _ChessBoardCardItems = new List<CardItem>();
    private List<CardItem> _HandCardItems = new List<CardItem>();
    // Awake
    protected override void OnAwake()
    {
        btn_Back_btn.onClick.AddListener(() =>
        {
            Close();
            FF8.Procedure.RunProcedureNode<MenuProcedure>();
        });

        btn_Send_btn.onClick.AddListener(() =>
        {
            _viewModel.TrySendTile();
        });
    }

    // 参数传入，每次打开UI都会执行
    protected override void OnAdded(int uiId, object[] args = null)
    {

    }

    // Start
    protected override void OnStart()
    {
        InitChessBoard();
        InitHand();

        _viewModel = new GameViewModel();
        _viewModel.ChessBoardList.CollectionChanged += OnTileListChanged;
        _viewModel.HandList.CollectionChanged += OnHandListChanged;
        _viewModel.PropertyChanged += OnPropertyChanged;
        _viewModel.GenerateTiles();
    }

    private void InitChessBoard()
    {
        _ChessBoardCardItems.Clear();
        for (int i = 0; i < ConstantModule.MAX_CHESS_BOARD_COUNT; i++)
        {
            GameObject go = FF8.GameObjectPool.Spawn(tf_CardPrefab_tf.gameObject, glg_ChessBoard_glg.transform);
            CardItem tileView = go.GetComponent<CardItem>();
            _ChessBoardCardItems.Add(tileView);
            go.SetActive(false);
        }
    }

    private void InitHand()
    {
        _HandCardItems.Clear();
        for (int i = 0; i < ConstantModule.MAX_HAND_COUNT; i++)
        {
            GameObject go = FF8.GameObjectPool.Spawn(tf_CardPrefab_tf.gameObject, hlg_CardGroupContainer_hlg.transform);
            CardItem tileView = go.GetComponent<CardItem>();
            _HandCardItems.Add(tileView);
            go.SetActive(false);
        }
    }

    private void OnTileListChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                int newIndex = e.NewStartingIndex;
                for (int i = 0; i < e.NewItems.Count; i++)
                {
                    MahjongTile tile = (MahjongTile)e.NewItems[i];
                    // 按照位置激活对应的CardItem
                    CardItem cardItem = _ChessBoardCardItems[newIndex];
                    cardItem.Refresh(tile, _viewModel); // 假设有一个方法用于初始化
                }
                break;

            case NotifyCollectionChangedAction.Remove:
                int oldIndex = e.OldStartingIndex;
                for (int i = 0; i < e.OldItems.Count; i++)
                {
                    CardItem cardItem = _ChessBoardCardItems[oldIndex];
                    cardItem.Clear();
                }
                break;
        }
    }

    private void OnHandListChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                int newIndex = e.NewStartingIndex;
                for (int i = 0; i < e.NewItems.Count; i++)
                {
                    MahjongTile tile = (MahjongTile)e.NewItems[i];
                    CardItem cardItem = _HandCardItems[newIndex];
                    cardItem.Refresh(tile, _viewModel);
                    cardItem.gameObject.SetActive(true);
                }
                break;
            case NotifyCollectionChangedAction.Remove:
                int oldIndex = e.OldStartingIndex;
                for (int i = 0; i < e.OldItems.Count; i++)
                {
                    CardItem cardItem = _HandCardItems[oldIndex];
                    cardItem.Clear();
                }
                break;
            case NotifyCollectionChangedAction.Reset:
                foreach (var cardItem in _HandCardItems)
                {
                    cardItem.Clear();    
                    cardItem.gameObject.SetActive(false);
                }
                break;
        }
    }

    private void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(_viewModel.MatchedRuleName))
        {
            txt_ComboTip_txt.text = _viewModel.MatchedRuleName;
        }
        if (e.PropertyName == nameof(_viewModel.MatchedScore))
        {
            txt_ScoreValue_txt.text = _viewModel.MatchedScore.ToString();
        }
    }

    protected override void OnViewTweenInit()
    {
        //transform.localScale = Vector3.one * 0.7f;
    }

    // 自定义打开界面动画
    protected override void OnPlayViewTween()
    {
        //transform.ScaleTween(Vector3.one, 0.1f).SetEase(Ease.Linear).SetOnComplete(OnViewOpen);
    }

    // 打开界面动画完成后
    protected override void OnViewOpen()
    {

    }

    // 删除之前，每次UI关闭前调用
    protected override void OnBeforeRemove()
    {

    }

    // 删除，UI关闭后调用
    protected override void OnRemoved()
    {

    }

    // 自动获取组件（自动生成，不能删除）
	[SerializeField] private UnityEngine.Transform tf_ScoreTitle_tf;
	[SerializeField] private UnityEngine.UI.Text txt_ScoreValue_txt;
	[SerializeField] private UnityEngine.UI.Text txt_ComboTip_txt;
	[SerializeField] private UnityEngine.UI.Button btn_Back_btn;
	[SerializeField] private UnityEngine.UI.Button btn_Rule_btn;
	[SerializeField] private UnityEngine.UI.GridLayoutGroup glg_ChessBoard_glg;
	[SerializeField] private UnityEngine.UI.HorizontalLayoutGroup hlg_CardGroupContainer_hlg;
	[SerializeField] private UnityEngine.UI.Button btn_Send_btn;
	[SerializeField] private UnityEngine.Transform tf_CardPrefab_tf;
	[SerializeField] private UnityEngine.UI.Button btn_Card_btn;
	[SerializeField] private UnityEngine.UI.Text txt_Name_txt;


	// 自动生成
	protected override void OnAddUIComponentListener()
	{
		btn_Back_btn?.AddButtonClickListener(ButtonClick);
		btn_Rule_btn?.AddButtonClickListener(ButtonClick);
		btn_Send_btn?.AddButtonClickListener(ButtonClick);
		btn_Card_btn?.AddButtonClickListener(ButtonClick);
	}

#if UNITY_EDITOR
	// 自动生成
	protected override void SetComponents()
	{
		tf_ScoreTitle_tf = transform.Find("tf_ScoreTitle").GetComponent<UnityEngine.Transform>();
		txt_ScoreValue_txt = transform.Find("txt_ScoreValue").GetComponent<UnityEngine.UI.Text>();
		txt_ComboTip_txt = transform.Find("txt_ComboTip").GetComponent<UnityEngine.UI.Text>();
		btn_Back_btn = transform.Find("btn_Back").GetComponent<UnityEngine.UI.Button>();
		btn_Rule_btn = transform.Find("btn_Rule").GetComponent<UnityEngine.UI.Button>();
		glg_ChessBoard_glg = transform.Find("glg_ChessBoard").GetComponent<UnityEngine.UI.GridLayoutGroup>();
		hlg_CardGroupContainer_hlg = transform.Find("hlg_CardGroupContainer").GetComponent<UnityEngine.UI.HorizontalLayoutGroup>();
		btn_Send_btn = transform.Find("btn_Send").GetComponent<UnityEngine.UI.Button>();
		tf_CardPrefab_tf = transform.Find("glg_ChessBoard/tf_CardPrefab").GetComponent<UnityEngine.Transform>();
		btn_Card_btn = transform.Find("glg_ChessBoard/tf_CardPrefab/btn_Card").GetComponent<UnityEngine.UI.Button>();
		txt_Name_txt = transform.Find("glg_ChessBoard/tf_CardPrefab/txt_Name").GetComponent<UnityEngine.UI.Text>();
	}
#endif
	// 自动获取组件（自动生成，不能删除）
}